package cn.lliiooll.launcher.thread;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import cn.lliiooll.launcher.log.LogOut;
import cn.lliiooll.launcher.update.Download;
import cn.lliiooll.launcher.update.Update;
import cn.lliiooll.launcher.update.Zip;
import cn.lliiooll.launcher.window.Window;

public class Down implements Runnable{
	
	public static long max;
	public static int maxbak;
	public static int maxmb;
	
	public Down(){
		Thread t =  new Thread(this,"down");
		t.start();
	}

	@SuppressWarnings("resource")
	@Override
	public void run() {
		try {
			Socket c = new Socket(Update.link,Update.port);
			DataInputStream ifs = new DataInputStream(c.getInputStream()); 
			OutputStream outs = c.getOutputStream();
			DataOutputStream out = new DataOutputStream(outs);
			File filepath1 = new File(Download.filepath);
			File file = new File(filepath1 + "\\" + Download.filename);
			if(!(filepath1.exists())) {
				filepath1.mkdir();
				if(!(file.exists())) {
					file.createNewFile();
					//InputStream in = new DataInputStream(ifs);
					FileOutputStream fos = new FileOutputStream(file);
							LogOut.info("正在下载");
							byte[] b = new byte[1024];
							int i = 0;
							out.writeInt(1);
							max = ifs.readLong();
							maxbak = (int) (max/1024);
							max = max/1024;
							max = max/1024;
							maxmb = (int) max;
							Window.ujpb.setMaximum(maxbak);
							Window.ujpb.setMinimum(1);
							while((i = ifs.read(b,0,b.length)) != -1) {
								fos.write(b, 0, i);
								Window.ujpb.setValue((int) (file.length()/1024));
								Window.ujpb.setString("已下载" + file.length()/1024/1024 + "/" + maxmb + "MB");
							}
							LogOut.info("下载完成");
							fos.flush();
							ifs.close();
							c.close();
							Zip.unZipFile(file, "tmp");
				}
			}

		} catch (UnknownHostException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
}